package com.share.tool.m2d.utils;

import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Auther: ybz
 * @Date: 2019/6/17 18:46
 * @Description:
 */
public class DateUtil {

    public static final String MM_DD = "MM-dd";
    public static final String YYYY_MM_DD = "yyyy-MM-dd";
    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";  
    public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
    public static final String MM_DD_HH_MM_SS = "MM-dd HH:mm:ss";
    public static final String HH_MM_SS = "HH:mm:ss";
    public static final String YYYYMMDD = "yyyyMMdd";
    public static final int SECOND = 0;
    public static final int MINUTE = 1;
    public static final int HOUR = 2;
    public static final int DAY = 3;
    public static final int MONTH = 4;
    public static final int YEAR = 5;

    /**
     * 增加天的方法
     *
     * @param date
     * @param x
     * @return
     */
    public static Date addDay(Date date, int x) {
        if (date == null)
            return date;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_YEAR, x);// 24小时制
        date = cal.getTime();
        cal = null;
        return date;
    }
    /**
     * 增加月的方法
     *
     * @param date
     * @param x
     * @return
     */
    public static Date addWeek(Date date, int x) {
        if (date == null)
            return date;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.WEEK_OF_YEAR, x);
        date = cal.getTime();
        cal = null;
        return date;
    }
    /**
     * 增加月的方法
     *
     * @param date
     * @param x
     * @return
     */
    public static Date addMonth(Date date, int x) {
        if (date == null)
            return date;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, x);
        date = cal.getTime();
        cal = null;
        return date;
    }
    /**
     * 增加月的方法
     *
     * @param date
     * @param x
     * @return
     */
    public static Date addYear(Date date, int x) {
        if (date == null)
            return date;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.YEAR, x);
        date = cal.getTime();
        cal = null;
        return date;
    }
    /**
     * 减少天的方法
     *
     * @param date
     * @param x
     * @return
     */
    public static Date subDay(Date date, int x) {
        if (date == null)
            return date;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_YEAR, -x);// 24小时制
        date = cal.getTime();
        cal = null;
        return date;
    }
    /**
     * 减少月的方法
     *
     * @param date
     * @param x
     * @return
     */
    public static Date subMonth(Date date, int x) {
        if (date == null)
            return date;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, -x);// 24小时制
        date = cal.getTime();
        cal = null;
        return date;
    }
    public static Date getCurrentDate() {
        return new Date();
    }


    /**
     * 获得指定日期的第一秒(yyyy-MM-dd 00:00:00:000)
     *
     * @param fullDate
     *            日期
     * @return 日期
     */
    public static Date getFirstSecondOfTheDay(Date fullDate) {
        if (null == fullDate) {
            return (Date) null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(fullDate);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 获得指定日期的最后一秒 (yyyy-MM-dd 23:59:59:000)
     *
     * @param fullDate
     *            日期
     * @return 日期
     */
    public static Date getLastSecondOfTheDay(Date fullDate) {
        if (null == fullDate) {
            return (Date) null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(fullDate);
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    public static String format(Date date, String pattern) {
        if (date == null) {
            return "";
        }
        if (StringUtils.isEmpty(pattern)) {
            return date.toString();
        }
        SimpleDateFormat formater = new SimpleDateFormat(pattern);
        return formater.format(date);
    }

    /**
     * 获取给定日期之间的所有日期
     * @param sDate
     * @param eDate
     * @return
     */
    public static List<String> getDays(Date sDate, Date eDate){
        List<String> resList = new ArrayList<String>();

        if((null == sDate) || (null == eDate) || sDate.after(eDate)){
            return null;
        }else{
            Date tmpDate = sDate;
            resList.add(DateUtil.format(sDate, DateUtil.YYYY_MM_DD));
            while(!DateUtil.isInSameDay(tmpDate = DateUtil.addDay(tmpDate, 1), eDate)){
                resList.add(DateUtil.format(tmpDate, DateUtil.YYYY_MM_DD));
            }
            resList.add(DateUtil.format(eDate, DateUtil.YYYY_MM_DD));

            return resList;
        }

    }

    public static boolean isInSameDay(Date sDate, Date eDate) {
        sDate = DateUtil.parseDate(DateUtil.format(sDate, DateUtil.YYYY_MM_DD));
        eDate = DateUtil.parseDate(DateUtil.format(eDate, DateUtil.YYYY_MM_DD));
        return sDate.equals(eDate);
    }

    /**
     * 将日期字符串解析成"yyyy-MM-dd"格式的Date对象
     *
     * @param dateTime
     *            日期字符串
     * @return （正确格式）日期对象
     * @throws ParseException
     */
    public static Date parseDate(String dateTime) {
        return parse(dateTime, YYYY_MM_DD);
    }

    /**
     * 将日期字符串解析成指定格式的Date对象
     *
     * @param dateTime
     *            日期字符串
     * @param format
     *            指定格式
     * @return （正确格式）日期对象
     * @throws ParseException
     */
    public static Date parse(String dateTime, String format) {
        if (dateTime == null || dateTime.length() <= 0)
            return null;
        String sDateTime = ((dateTime.indexOf('.') > 0)) ? dateTime.substring(0, dateTime.indexOf('.')) : dateTime;
        DateFormat dateFormat = new SimpleDateFormat(format);
        try {
            return dateFormat.parse(sDateTime);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 比较时间,如果sDate比eDate早,则返回1,sDate比eDate晚则返回-1,相等返回0
     *
     * @param sDate
     * @param eDate
     * @return
     */
    public static Integer compareDate(Date sDate, Date eDate) {
        Long resBalance = calcDateBalance(sDate, eDate);
        Integer res = null;
        if (resBalance > 0) {
            res = 1;
        } else if (resBalance < 0) {
            res = -1;
        } else {
            res = 0;
        }
        return res;
    }

    public static Long calcDateBalance(Date sDate, Date eDate) {
        Long res = null;
        Long sDateAsLong = sDate.getTime();
        Long eDateAsLong = eDate.getTime();
        res = eDateAsLong - sDateAsLong;
        return res;
    }
    public static Date stringToDate(String strDate, String pattern) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.parse(strDate);
    }
    public static Date stringToDateUTC(String strDate) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss+08:00");//"2018-04-03T17:17:23+08:00" yyyy-MM-dd'T'HH:mm:ss
       // df.setTimeZone(TimeZone.getTimeZone("UTC"));
        return df.parse(strDate);
    }
    public static String dateToStringUTC(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss+08:00");//"2018-04-03T17:17:23+08:00" yyyy-MM-dd'T'HH:mm:ss
        //df.setTimeZone(TimeZone.getTimeZone("UTC"));
        return df.format(date);
    }
    public static String dateToString(Date date, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }
    /**
     * 获取两个时间的差值 单位:天数 默认毫秒
     *
     * @param date1
     * @param date2
     * @param timeUnit
     * <br/>
     *            时间单位：<b>DateUtil.SECOND,DateUtil.MINUTE,DateUtil.HOUR,DateUtil
     *            .DAY,DateUtil.MONTH,DateUtil.YEAR<b>
     * @return
     */
    public static long getDiffDate(Date date1, Date date2, int timeUnit) {
        long diffTime = Math.abs(date1.getTime() - date2.getTime());
        switch (timeUnit) {
            case SECOND:
                diffTime = diffTime / 1000;
                break;
            case MINUTE:
                diffTime = diffTime / 60000;
                break;
            case HOUR:
                diffTime = diffTime / 3600000L;
                break;
            case DAY:
                diffTime = diffTime / 86400000L;
                break;
            case MONTH:
                diffTime = diffTime / 2592000000L;
                break;
            case YEAR:
                diffTime = diffTime / 946080000000L;
                break;
            default:
                break;
        }
        return diffTime;
    }

    public static Date addHours(Date date, int x) {
        if (date == null) {
            return null;
        } else {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(11, x);
            return cal.getTime();
        }
    }

    public static void main(String[] args) {
        try {

//            Date tiem= DateUtil.stringToDateUTC("2019-08-06T11:21:38+08:00");//2019-08-06T11:21:38+08:00
//            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String sDate=sdf.format(tiem);
//            System.out.println(sDate);
//            Date sDatew=DateUtil.stringToDate(sDate,"yyyy-MM-dd HH:mm:ss");
//            System.out.println(DateUtil.dateToStringUTC(sDatew));
////            Date sysDate=DateUtil.getCurrentDate();
////            System.out.println(DateUtil.dateToString(DateUtil.addDay(sysDate,-7),"yyyy-MM-dd HH:mm:ss"));
////            System.out.println(DateUtil.dateToString(DateUtil.addWeek(sysDate,-1),"yyyy-MM-dd HH:mm:ss"));
////            System.out.println(DateUtil.dateToString(DateUtil.addMonth(sysDate,-1),"yyyy-MM-dd HH:mm:ss"));
////            System.out.println(DateUtil.dateToString(DateUtil.addYear(sysDate,-1),"yyyy-MM-dd HH:mm:ss"));
////            System.out.println(DateUtil.dateToString(DateUtil.subDay(sysDate,365),"yyyy-MM-dd HH:mm:ss"));
////            System.out.println(DateUtil.dateToString(DateUtil.subMonth(sysDate,1),"yyyy-MM-dd HH:mm:ss"));
////            Long memberCount=10001L;
////            int pageSize = 10000;//定义每页的条数
////            //计算循环次数，即总页数  Math.ceil为向上取整
////            int pages = (int) Math.ceil(memberCount/(pageSize*1.0));
////            System.out.println(pages);
//            String aa="343aa";
//            String bb=":";
//            System.out.println(aa.concat(bb).concat("s1111").concat("2333"));




        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    private final static SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
    private final static SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    /**
     * 获取本周开始时间
     * @return
     */
    public static Date getBeginDayOfWeek() {
      Date date = new Date();
      Calendar cal = Calendar.getInstance();
      cal.setTime(date);
      int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
      if (dayofweek == 1) {
          dayofweek += 7;
      }
      cal.add(Calendar.DATE, 2 - dayofweek);
      return  cal.getTime();
    }
     
    /**
     * 获取本周结束时间
     * @return
     */
    public static Date getEndDayOfWeek(){
       Calendar cal = Calendar.getInstance();
       cal.setTime(getBeginDayOfWeek());
       cal.add(Calendar.DAY_OF_WEEK, 6);
       Date weekEndSta = cal.getTime();
       return weekEndSta;
    }
    
    
    /**
     * 获得本月的开始时间
     *
     * @return
     */
    public static Date getMonthStartTime(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        Date dt = null;
        try {
            c.set(Calendar.DATE, 1);
            dt = shortSdf.parse(shortSdf.format(c.getTime())); 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dt;
    }
 
    /**
     * 本月的结束时间
     *
     * @return
     */
    public static Date getMonthEndTime(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        Date dt = null;
        try {
            c.set(Calendar.DATE, 1);
            c.add(Calendar.MONTH, 1);
            c.add(Calendar.DATE, -1);
            dt = longSdf.parse(shortSdf.format(c.getTime()) + " 23:59:59");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dt;
    }
    
    /**
     * String 转 Date
     * @return
     */
    public static Date getStringToDateHHssmm(String data) {
    	DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm"); 
    	Date date = null;   
    	try {   
    	    date = format.parse(data);  // Thu Jan 18 00:00:00 CST 2007   
    	} catch (ParseException e) {   
    	    e.printStackTrace();   
    	}   
    	return date;
    }
    
    /**
     * 获取自定义时间，往前的时间，当前时间前几天。
     * @return
     */
    public static String getDate(int day) {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
     	Calendar c = Calendar.getInstance();         
     	c.add(Calendar.DATE, - day);         
     	Date monday = c.getTime();       
     	String preMonday = sdf.format(monday); 
     	return preMonday;
    }
    
    /**
          *  获取当时时间
     * @return
     */
    public static String getStringDate() {
 	   Date currentTime = new Date();
 	   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 	   String dateString = formatter.format(currentTime);
 	   System.out.println(dateString);
 	  return dateString;
    }
    
    /**
     * String转Date
     * @param data
     * @return
     */
    public static Date getStringToDateHHssmm1(String data) {
    	Date date = new Date();
    	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
    	String dt = simpleDateFormat.format(date);
    	
    	DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm"); 
    	Date dateD = null;   
    	try {   
    		dateD = format.parse(dt);  // Thu Jan 18 00:00:00 CST 2007   
    	} catch (ParseException e) {   
    	    e.printStackTrace();   
    	}   
    	return dateD;
    }
    
    /**  
	 * 计算两个日期之间相差的天数  
	 * @param smdate 较小的时间 
	 * @param bdate  较大的时间 
	 * @return 相差天数 
	 * @throws ParseException  
	 */
	public static int daysBetween(Date smdate, Date bdate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
		smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));
		System.out.println(smdate);
		System.out.println(bdate);
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);
		return Integer.parseInt(String.valueOf(between_days));
	}

    public static String strDateTimeToEsUtc(String strDate) {
        String re = strDate;
        if (StringUtils.hasText(strDate)) {
            re = strDate.replace(" ", "T") + "+08:00"; //转utc
        }
        return re;
    }
}